import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, Space, message, Divider } from 'antd';
import { SettingOutlined, SaveOutlined } from '@ant-design/icons';

export interface CozeConfig {
  token: string;
  botId: string;
  baseUrl: string;
}

interface CozeConfigProps {
  onConfigChange: (config: CozeConfig) => void;
  initialConfig?: Partial<CozeConfig>;
}

const CozeConfigComponent: React.FC<CozeConfigProps> = ({ 
  onConfigChange, 
  initialConfig 
}) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  // 默认配置
  const defaultConfig: CozeConfig = {
    token: '',
    botId: '',
    baseUrl: 'https://api.coze.cn',
    ...initialConfig
  };

  useEffect(() => {
    // 从localStorage加载配置
    const savedConfig = localStorage.getItem('coze-config');
    if (savedConfig) {
      try {
        const config = JSON.parse(savedConfig);
        form.setFieldsValue(config);
        onConfigChange(config);
      } catch (error) {
        console.error('加载配置失败:', error);
      }
    } else {
      form.setFieldsValue(defaultConfig);
    }
  }, [form, onConfigChange]);

  const handleSave = async (values: CozeConfig) => {
    setLoading(true);
    try {
      // 保存到localStorage
      localStorage.setItem('coze-config', JSON.stringify(values));
      
      // 通知父组件配置变更
      onConfigChange(values);
      
      message.success('配置保存成功');
    } catch (error) {
      console.error('保存配置失败:', error);
      message.error('保存配置失败');
    } finally {
      setLoading(false);
    }
  };

  const handleReset = () => {
    form.setFieldsValue(defaultConfig);
    localStorage.removeItem('coze-config');
    onConfigChange(defaultConfig);
    message.info('配置已重置');
  };

  return (
    <Card 
      title={
        <Space>
          <SettingOutlined />
          Coze 配置
        </Space>
      }
      className="config-section"
      style={{ marginBottom: '20px' }}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSave}
        initialValues={defaultConfig}
      >
        <Form.Item
          label="API Token"
          name="token"
          rules={[
            { required: true, message: '请输入Coze API Token' },
            { min: 10, message: 'Token长度至少10个字符' }
          ]}
          extra="在Coze平台获取的API访问令牌"
        >
          <Input.Password 
            placeholder="请输入Coze API Token" 
            autoComplete="off"
          />
        </Form.Item>

        <Form.Item
          label="Bot ID"
          name="botId"
          rules={[
            { required: true, message: '请输入Bot ID' },
            { pattern: /^\d+$/, message: 'Bot ID应该是数字' }
          ]}
          extra="用于图片分析的Bot ID"
        >
          <Input placeholder="请输入Bot ID" />
        </Form.Item>

        <Form.Item
          label="API Base URL"
          name="baseUrl"
          rules={[
            { required: true, message: '请输入API Base URL' },
            { type: 'url', message: '请输入有效的URL' }
          ]}
          extra="Coze API的基础URL，默认为官方地址"
        >
          <Input placeholder="https://api.coze.cn" />
        </Form.Item>

        <Divider />

        <Form.Item>
          <Space>
            <Button 
              type="primary" 
              htmlType="submit" 
              loading={loading}
              icon={<SaveOutlined />}
            >
              保存配置
            </Button>
            <Button onClick={handleReset}>
              重置配置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <div className="config-help">
        <h4>配置说明：</h4>
        <ul>
          <li><strong>API Token:</strong> 在Coze平台的开发者设置中获取</li>
          <li><strong>Bot ID:</strong> 创建的Bot的唯一标识符</li>
          <li><strong>Base URL:</strong> API服务地址，通常使用默认值即可</li>
        </ul>
      </div>
    </Card>
  );
};

export default CozeConfigComponent;